﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using viBook.Models;

namespace viBook.Controllers
{
    public class CategoriesController : BaseController
    {
        #region Constructors and Repository vars

        private readonly ICategoryRepository _categoryRepository;

        public CategoriesController()
            : this(new CategoryRepository())
        {
        }

        public CategoriesController(ICategoryRepository categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        #endregion

        public ViewResult Index()
        {
            return View(_categoryRepository.All);
        }
  

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Books/Create

        [HttpPost]
        public ActionResult Create(Category category)
        {
            if (ModelState.IsValid)
            {
                _categoryRepository.InsertOrUpdate(category);
                _categoryRepository.Save();
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult Edit(Category category)
        {
            if (ModelState.IsValid)
            {
                _categoryRepository.InsertOrUpdate(category);
                _categoryRepository.Save();
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            _categoryRepository.Delete(id);
            _categoryRepository.Save();

            return RedirectToAction("Index");
        }


        public string Search(string q, int limit)
        {
            var result = _categoryRepository.FindCategories(q, limit);
            return String.Join(Environment.NewLine, result);
        }
    }
}